<?php

namespace app\sapi\controller\v1;


use app\common\controller\Api;
use addons\third\library\Service;
use addons\third\model\Third;
use app\admin\model\Admin;
use app\admin\model\Shop;
use app\admin\model\ShopFollow;
use app\admin\model\ShopPlatform;
use app\common\model\Config as configs;
use app\common\model\User as UserModel;
use app\common\model\UserShareImage;
use app\common\library\Image;
use fast\Random;
use think\Cache;
use think\Config;
use think\Db;
use think\Exception;
use think\Hook;


// use think\Request;
use wechat\AccessToken;
use wechat\Wechat;


/**
 * 商家
 * Class Business
 * @package app\sapi\controller\v1
 */
class Business extends Api
{
    protected $noNeedLogin = ['getApplyParam','login', 'wxminprogramlogin','wxOfficialAccountBaseLogin','authorize'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        //监听登录成功的事件
        Hook::add('business_login_successed', function ($shop) use ($auth) {

        });
        //监听退出登陆的事件
        Hook::add('business_logout_successed', function ($shop) use ($auth) {

        });
    }

    /**
     * h5登录
     * @DateTime 2023-04-20T15:21:15+0800
     * @return   [type]                   [description]
     */
    public function wxOfficialAccountBaseLogin()
    {
        $platform = $this->request->post("platform", 'wechat');
        $code = input('code');
        $shop_no = input('shop_no','');// 如果有店铺编号，需要绑定对应商家
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $shop = [];
        if ($shop_no) {
            $shop = Db::name('shop')->where('shop_no',$shop_no)->field('have_uid,phone')->find();
            if (!$shop) $this->error('店铺不存在');
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $platformObj = $app->{$platform};
        $result = $platformObj->getAccessToken($code);
            // var_dump($result);exit;
        $openid = $result['openid'];
        if (empty($openid)) {
            $this->error('登陆失败', '', 400, 'json', ['statuscode' => 200]);
        }
        Db::startTrans();
        // try {
            $wechatUserInfo = $platformObj->getUserInfo($result);
            // 绑定后台创建的商家
            if ($shop) {
                $user = (new UserModel())->where(['id' => $shop['have_uid'],'user_type'=>1])->find();
                if (isset($user) && $user) {
                    if ($user->status != 'normal') {
                        $this->error(__('Account is locked'));
                    }
                    // 如果店铺绑定的商家openid和当前用户授权openid相同，直接登陆
                    if ($user['openid'] && $user['openid']==$openid) {
                        $ret = $this->auth->direct($user->id);
                    // 如果店铺绑定的商家openid和当前用户授权openid不同
                    } elseif ($user['openid'] && $user['openid']!=$openid) {
                        $users = (new UserModel())->where(['openid' => $openid,'user_type'=>1,'status'=>'normal'])->find();
                        // 当前微信没有授权过，则注册然后正常支付账单
                        if (!$users) {
                            $username = getUniqueUsername();
                            $extend = [
                                'openid' => $openid,
                                'nickname' => $wechatUserInfo['userinfo']['nickname'] ?? '微信用户',
                                'avatar' => $wechatUserInfo['userinfo']['avatar'] ?? "http://oss.chbcplus.com/uploads/20230420/f57ebce8a72b823912904fe76eda0909.png",
                                'gender' => 0,
                                'pid' => input('pid/d', 0),
                                'unionid' => '',
                                'user_type' => 1
                            ];
                            $ret = $this->auth->register($username, Random::alnum(), '', '', $extend);
                        // 当前微信授权过，则直接登陆
                        } else {
                            $ret = $this->auth->direct($users->id);
                        }
                    // 如果店铺绑定的商家没有openid，则查询当前微信号有没有授权过
                    } elseif (!$user['openid']) {
                        $users = (new UserModel())->where(['openid' => $openid,'user_type'=>1,'status'=>'normal'])->find();
                        // 当前微信没有授权过，则绑定当前微信账号和商家账号
                        if (!$users) {
                            $ip = request()->ip();
                            $time = time();
                            $data = [
                                'openid' => $openid,
                                'nickname' => $wechatUserInfo['userinfo']['nickname'] ?? '微信用户',
                                'avatar' => $wechatUserInfo['userinfo']['avatar'] ?? "http://oss.chbcplus.com/uploads/20230420/f57ebce8a72b823912904fe76eda0909.png",
                                'gender' => 0,
                                'pid' => input('pid/d', 0),
                                'unionid' => '',
                                'user_type' => 1,
                                'username' => getUniqueUsername(),
                                'salt'      => \fast\Random::alnum(),
                                'jointime'  => $time,
                                'joinip'    => $ip,
                                'logintime' => $time,
                                'loginip'   => $ip,
                                'prevtime'  => $time,
                            ];
                            $user->save($data);
                            $ret = $this->auth->direct($user->id);
                        // 当前微信授权过
                        } else {
                            // 如果和其他店铺绑定过，则直接登录
                            if (Db::name('shop')->where(['have_uid'=>$users['id']])->find()) {
                                $ret = $this->auth->direct($users->id);
                            // 如果和其他店铺没有绑定过，则删除该账号再重新绑定
                            } else {
                                $users->status = 'delete';
                                $users->save();
                                $ip = request()->ip();
                                $time = time();
                                $data = [
                                    'openid' => $openid,
                                    'nickname' => $wechatUserInfo['userinfo']['nickname'] ?? '微信用户',
                                    'avatar' => $wechatUserInfo['userinfo']['avatar'] ?? "http://oss.chbcplus.com/uploads/20230420/f57ebce8a72b823912904fe76eda0909.png",
                                    'gender' => 0,
                                    'pid' => input('pid/d', 0),
                                    'unionid' => '',
                                    'user_type' => 1,
                                    'username' => getUniqueUsername(),
                                    'salt'      => \fast\Random::alnum(),
                                    'jointime'  => $time,
                                    'joinip'    => $ip,
                                    'logintime' => $time,
                                    'loginip'   => $ip,
                                    'prevtime'  => $time,
                                ];
                                $user->save($data);
                                $ret = $this->auth->direct($user->id);
                            }
                        }
                    }
                } else {
                    $this->error('授权有误');
                }
            } else {
                $user = (new UserModel())->where(['openid' => $openid,'user_type'=>1,'status'=>'normal'])->find();
                if (isset($user) && $user) {
                    if ($user->status != 'normal') {
                        $this->error(__('Account is locked'));
                    }
                    //如果已经有账号则直接登录
                    $ret = $this->auth->direct($user->id);
                } else {
                    $username = getUniqueUsername();
                    $extend = [
                        'openid' => $openid,
                        'nickname' => $wechatUserInfo['userinfo']['nickname'] ?? '微信用户',
                        'avatar' => $wechatUserInfo['userinfo']['avatar'] ?? "http://oss.chbcplus.com/uploads/20230420/f57ebce8a72b823912904fe76eda0909.png",
                        'gender' => 0,
                        'pid' => input('pid/d', 0),
                        'unionid' => '',
                        'user_type' => 1
                    ];
                    $ret = $this->auth->register($username, Random::alnum(), '', '', $extend);
                }
            }
            //用户注册成功
            if ($ret) {
                $userInfo = (new UserModel())->where('id', $this->auth->id)->find();
                $userWechat = (new Third())->where(['user_id' => $userInfo['id'], 'openid' => $openid])->find();
                if (!$userWechat) {
                    $data = $userInfo->toArray();
                    //微信用户表添加记录
                    $data['platform'] = 'h5';
                    $data['user_id'] = $data['id'];
                    $data['openid'] = $openid;
                    $data['access_token'] = '';
                    $data['refresh_token'] = '';
                    $data['expires_in'] = 3600 * 24 * 7;
                    $data['unionid'] = $unionid ?? '';
                    unset($data['id']);
                    Service::connect('wechat', $data);
                }
                $userInfo = $this->auth->getUserinfo();
                $userInfo['session_key'] = '';
                Db::commit();
                $this->success(__('Logged in successful'), $userInfo);
            } else {
                Db::rollback();
                $this->error($this->auth->getError());
            }
        // } catch (Exception $e) {
        //     Db::rollback();
        //     \think\Log::write('商户h5:'.$e->getMessage());
        //     $this->error('登陆失败');
        // }
        $this->success('', $data);
    }

    public function wxMinProgramLogin()
    {
        $code = input('code', '');
        $pid = input('pid/d', 0);
        if (!$code) $this->error('自动登陆失败');
        $appid = Config::get('shop.appid');
        $appSecret = Config::get('shop.appsecret');

        $wechat = new Wechat($appid, $appSecret);
        $wechatUserInfo = $wechat->code2Session($code);
        \think\Log::write('小程序userinfo:'.json_encode($wechatUserInfo));
        if (isset($wechatUserInfo['errcode']) && $wechatUserInfo['errcode'] !== 0) {
            $this->error('获取用户信息失败', '', 400, 'json', ['statuscode' => 200]);
        }
        $sessionKey = $wechatUserInfo['session_key'];
        $openid = $wechatUserInfo['openid'];
        $unionid = $wechatUserInfo['unionid'];
        // $sessionKey = 'pEJRIRy0rBz7DjC0T+FmyA==';
        // $openid = 'op5kO5QrbSP9pWPY0aSgCOrWEwN8';
        // $unionid = 'oC_s565kq7a-XFjUITxyOZdHBcmA';
        if (empty($openid) || empty($sessionKey)) {
            $this->error('登陆失败', '', 400, 'json', ['statuscode' => 200]);
        }
        Db::startTrans();
        try {
            $user = (new UserModel())->where(['unionid' => $unionid,'user_type'=>1])->find();
            if ($user) {
                if ($user->status != 'normal') {
                    $this->error('账号被封禁');
                }
                // third表有没有数据
                $third = (new Third())->where(['unionid'=>$unionid,'openid'=>$openid,'platform'=>'miniprogram'])->find();
                if (!$third) {
                    $third = new Third();
                    $thirddata['platform'] = 'miniprogram';
                    $thirddata['openname'] = '';
                    $thirddata['user_id'] = $user->id;
                    $thirddata['openid'] = $openid;
                    $thirddata['access_token'] = '';
                    $thirddata['refresh_token'] = '';
                    $thirddata['expires_in'] = 3600 * 24 * 7;
                    $thirddata['unionid'] = $unionid;
                    $third->create($thirddata);
                }
                //如果已经有账号则直接登录
                $ret = $this->auth->direct($user->id);
            } else {
                $username = $openid;
                $password = Random::alnum();
                $extend = [
                    'openid' => $openid,
                    'nickname' => '微信用户',
                    'pid' => $pid > 0 ? $pid : 0,
                    'unionid' => $unionid ?? '',
                    'user_type'=>1
                ];
                $mobile = '';
                if ($extend['unionid'] != '') {
                    $third = (new Third())->alias('t')->join('chbc_user u','t.user_id=u.id')->field('u.*,t.user_id')->where(['t.unionid'=>$extend['unionid']])->order('u.avatar desc')->find();
                    if ($third && $third['user_id'] > 0) {
                        if ($third['mobile'] != '') $mobile = $third['mobile'];
                        if ($third['nickname'] != '' && $third['avatar'] != '') {
                            $extend['nickname'] = $third['nickname'];
                            $extend['avatar'] = $third['avatar'];
                        }
                    }
                }
                $ret = $this->auth->register($username, $password, '', $mobile, $extend);
                if (!$ret) {
                    $this->error('注册失败，请联系管理员');
                }
                $user = (new UserModel())->where(['openid' => $openid,'unionid' => $unionid,'user_type'=>1])->find();
                // third表有没有数据
                $third = (new Third())->where(['unionid'=>$unionid,'openid'=>$openid,'platform'=>'miniprogram'])->find();
                if (!$third) {
                    $third = new Third();
                    $thirddata['platform'] = 'miniprogram';
                    $thirddata['openname'] = $extend['nickname'];
                    $thirddata['user_id'] = $user->id;
                    $thirddata['openid'] = $openid;
                    $thirddata['access_token'] = '';
                    $thirddata['refresh_token'] = '';
                    $thirddata['expires_in'] = 3600 * 24 * 7;
                    $thirddata['unionid'] = $unionid;
                    $third->create($thirddata);
                }
            }
            $user['token'] = $this->auth->getToken();
            Db::commit();
            $this->success('登陆成功',$user);
        } catch (Exception $e) {
            Db::rollback();
            $this->error('登陆失败');
        }
    }


    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success('退出成功', null, 200);
    }

    /**
     * 获取商家信息
     */
    public function info()
    {
        // $user = (new UserModel())->where(['id' => $this->auth->id,'user_type'=>1])->find();
        $user = (new UserModel())->where(['id' => $this->auth->id])->find();
        if (empty($user)) $this->error('商家不存在');
        $user['token'] = $this->auth->getToken();
        $user['bio'] = Shop::where(['have_uid'=>$user['id'],'shop_status'=>1])->limit(3)->select();
        //今日订单量
        $time0 = strtotime(date("Y-m-d", time()));
        $time24 = $time0 + 86400;

        // $orderNum = (new \app\common\model\Order())->where([
        //     'user_id' => ['=', $this->auth->id],
        //     'place_time' => ['between', [$time0, $time24]]
        // ])
        //     ->count();
        // $totalMoney = (new BusinessWalletLog())->where([
        //     'business_id' => ['=', $this->auth->id],
        //     'createtime' => ['between', [$time0, $time24]],
        //     'wallet' => ['<', 0],
        //     'wallet_type' => ['=', 2]
        // ])
        //     ->sum('wallet');
        // $businessInfo['today_order_num'] = $orderNum;
        // $businessInfo['today_total_money'] = abs($totalMoney);
        $this->success('商家信息', $user);
    }

    /**
     * 店铺列表
     * @DateTime 2023-03-22T10:23:56+0800
     * @return   [type]                   [description]
     */
    public function shopList()
    {
        $shop_status = input('shop_status/d',9);//9表示全部
        $page = input('page/d',1);
        $page_num = 100;
        if ($this->auth->user_type!=1) {
            $this->error('您不是商家');
        }
        $user_id = $this->auth->id;
        // 查询是不是中间人，如果是中间人查询中间人介绍的店铺
        // $middleman = Db::name('middleman')->where('user_id',$user_id+config('virtual_userid'))->find();
        // if ($middleman) {
        //     $where = ['shop_status'=>['>=',0]];
        //     $where['middleman_id'] = ['=',$middleman['id']];
        //     if ($shop_status!=9) {
        //         $where['shop_status'] = ['=',$shop_status];
        //     }
        //     $where['delete_dt'] = ['null',''];
        // } else {
            $where = ['shop_status'=>['>=',0]];
            $where['have_uid'] = ['=',$user_id];
            if ($shop_status!=9) {
                $where['shop_status'] = ['=',$shop_status];
            }
            $where['delete_dt'] = ['null',''];
        // }
        $list = Shop::where($where)->with(['platform'])->page($page,$page_num)->select();
        foreach ($list as $key => $value) {
            $value->getRelation('platform')->visible(['qrcode_pic','platform_no']);
        }
        $total = Shop::where($where)->count();
        $total_page = ceil($total/$page_num);
        $this->success('店铺列表', ['list'=>$list,'total_page'=>$total_page,'total'=>$total]);
    }

    /**
     * 店铺详细
     * @DateTime 2023-03-22T10:38:28+0800
     * @return   [type]                   [description]
     */
    public function shopDetail()
    {
        $id = input('id/d', 0);
        if (!$id) {
            $this->error('缺少参数');
        }
        $where = [];
        $where['s.have_uid'] = ['=',$this->auth->id];
        $where['s.shop_status'] = ['=',1];
        $where['s.delete_dt'] = ['null',''];
        $where['s.id'] = ['=',$id];
        $info = Shop::where($where)->alias('s')->field('s.*,sp.qrcode_pic,sp.qrcode_pic as qrcode_pic_url,sp.platform_no')->join('chbc_shop_platform sp','sp.shop_no=s.shop_no')->find();
        $info['qrcode_pic_url'] = config('upload_domain').$info['qrcode_pic_url'];
        $this->success('店铺详情', $info);
    }

    public function update()
    {
        $nickName = input('nickName', '','htmlspecialchars');
        $avatarUrl = input('avatarUrl', '','htmlspecialchars');
        $data = ['updatetime' => time()];
        if ($nickName != '') $data['nickname'] = $nickName;
        if ($avatarUrl != '') $data['avatar'] = $avatarUrl;
        try {
            $user = (new \app\common\model\User())->where(['id' => $this->auth->id])->find();
            $res = $user->allowField(true)
                ->isUpdate(true)
                ->save($data);
            if (!$res) $this->error('更新失败');
            $this->success('更新成功', $res);
        } catch (Exception $exception) {
            $this->error('更新失败');
        }
    }

    /**
     * 申请店铺第一步
     * @DateTime 2023-03-20T19:33:52+0800
     * @return   [type]                   [description]
     */
    public function apply()
    {
        $data = [
            'shop_type' => input('shop_type', '','htmlspecialchars'),
            'shop_name' => input('name', '','htmlspecialchars'),
            'category_no' => input('category_id', '','htmlspecialchars'),
            'contact_user' => input('contact_user', '','htmlspecialchars'),
            'phone' => input('mobile', '','htmlspecialchars'),
            'address' => input('address', '','htmlspecialchars'),
            'address2' => input('address2', '','htmlspecialchars'),
            'lat' => input('latitude', ''),
            'lng' => input('longitude', ''),
            'invite_code' => input('invite_code', '','htmlspecialchars'),
            'logo_pic' => input('logo', '','htmlspecialchars'),
            'business_time_no' => input('business_time_no', '','htmlspecialchars'),
            'business_time' => input('business_time'),
        ];
        if ($data['shop_type']!='1' && $data['shop_type']!='2' && $data['shop_type']!='1,2') {
            $this->error('店铺类型有误');
        }
        $rule = [
            'shop_type' => "require",
            'shop_name' => "require|max:30",
            'logo_pic' => "require|max:150",
            'contact_user' => "require",
            'phone' => "require",
            'address' => "require|max:100",
            'lat' => "require|float",
            'lng' => "require|float",
        ];
        $msg = [
            'shop_type.require' => '店铺类型有误',
            'shop_name.require' => '请填写店铺名称',
            'shop_name.max' => '店铺名称为2到15个字',
            'logo_pic.require' => '请上传logo',
            'logo_pic.max' => '请上传logo',
            'contact_user.require' => '请填写联系人',
            'phone.require' => '请填写手机号',
            'address.require' => '请填写地址',
            'address.max' => '地址过长',
            'lat.require' => '请选择地址',
            'lat.float' => '请选择地址',
            'lng.require' => '请选择地址',
            'lng.float' => '请选择地址',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) $this->error($validate->getError());

        $shop_type = explode(',', $data['shop_type']);
        $invite_code = $data['invite_code'];
        $data['salesman_admin_id'] = 0;
        if ($invite_code) {
            $data['salesman_admin_id'] = (int)Admin::where('salt',$invite_code)->value('id');
        }
        // $data['business_time'] = json_encode($data['business_time']);
        $model = new Shop();
        unset($data['shop_type']);
        unset($data['invite_code']);
        $return = [];
        Db::startTrans();
        try {
            foreach ($shop_type as $key => $value) {
                $save = array_merge($data, [
                    'have_uid' => $this->auth->id,
                    'submit_by' => $this->auth->id,
                    // 'have_uid' => 1,
                    // 'submit_by' => 1,
                    'shop_status' => 0,
                    'shop_type' => $value
                ]);
                $save['shop_no'] = $this->generateNo(['biz_tag'=>'shop_no','len'=>10,'int_prefix'=>1]);
                $result = $model->allowField(true)->save($save);
                $return[$key] = $model['id'];
                // 跟进业务员
                if ($save['salesman_admin_id']) {
                    ShopFollow::create([
                        'shop_no' => $save['shop_no'],
                        'follow_admin_id' => $save['salesman_admin_id'],
                        'is_head' => 1,
                    ]);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            \think\Log::write($_SERVER['REQUEST_URI'].'=>Exception:'.$e->getMessage());
            $this->error('店铺提交失败');

        }
        $this->success('提交成功',$return);
    }

    /**
     * 申请店铺第二步
     * @DateTime 2023-03-20T19:34:10+0800
     * @return   [type]                   [description]
     */
    public function applyTwo()
    {
        $data = [
            'id' => input('id', '','htmlspecialchars'),
            'business_license_pic' => input('business_license_pic', '','htmlspecialchars'),
            'qrcode_pic' => input('qrcode', '','htmlspecialchars'),
        ];
        $rule = [
            'id' => "require",
            'business_license_pic' => "require|max:150",
            'qrcode_pic' => "require|max:150",
        ];
        $msg = [
            'id.require' => '参数有误',
            'business_license_pic.require' => '请上传营业执照照片',
            'business_license_pic.max' => '请上传营业执照照片',
            'qrcode_pic.require' => '请上传小程序码',
            'qrcode_pic.max' => '请上传小程序码',
        ];
        $id = explode(',', $data['id']);
        if (!count($id)) {
            $this->error('店铺参数有误');
        }
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) $this->error($validate->getError());

        Db::startTrans();
        try {
            foreach ($id as $key => $value) {
                $shop = Shop::where(['id'=>$value,'shop_status'=>0])->find();
                if (!$shop) {
                    $this->error('初始提交信息出错');
                }
                $shop->business_license_pic = $data['business_license_pic'];
                $shop->save();
                // 平台信息
                ShopPlatform::create([
                    'shop_no' => $shop['shop_no'],
                    // 'platform_no' => $data['platform_no'],
                    'qrcode_pic' => $data['qrcode_pic'],
                ]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            \think\Log::write($_SERVER['REQUEST_URI'].'=>Exception:'.$e->getMessage());
            $this->error('店铺提交失败');

        }
        $this->success('提交成功');
    }


    /**
     * 修改店铺信息
     * @DateTime 2023-04-04T18:13:00+0800
     * @return   [type]                   [description]
     */
    public function editShop()
    {
        $data = [
            'id' => input('id/d', '','htmlspecialchars'),
            'shop_type' => input('shop_type/d', 0),
            'shop_name' => input('name', '','htmlspecialchars'),
            'category_no' => input('category_id', '','htmlspecialchars'),
            'contact_user' => input('contact_user', '','htmlspecialchars'),
            'phone' => input('mobile', '','htmlspecialchars'),
            'address' => input('address', '','htmlspecialchars'),
            'address2' => input('address2', '','htmlspecialchars'),
            'lat' => input('latitude', ''),
            'lng' => input('longitude', ''),
            'invite_code' => input('invite_code', '','htmlspecialchars'),
            'logo_pic' => input('logo', '','htmlspecialchars'),
            'business_time_no' => input('business_time_no', '','htmlspecialchars'),
            'business_time' => input('business_time'),
            'business_license_pic' => input('business_license_pic', '','htmlspecialchars'),
            'qrcode_pic' => input('qrcode', '','htmlspecialchars'),
        ];
        if ($data['shop_type']!='1' && $data['shop_type']!='2') {
            $this->error('店铺类型有误');
        }
        $rule = [
            'id' => "require",
            'shop_type' => "require",
            'shop_name' => "require|max:30",
            'logo_pic' => "require|max:150",
            'contact_user' => "require",
            'phone' => "require",
            'address' => "require|max:100",
            'lat' => "require|float",
            'lng' => "require|float",
            'business_license_pic' => "require|max:150",
            'qrcode_pic' => "require|max:150",
        ];
        $msg = [
            'id.require' => '参数有误',
            'shop_type.require' => '店铺类型有误',
            'shop_name.require' => '请填写店铺名称',
            'shop_name.max' => '店铺名称为2到15个字',
            'logo_pic.require' => '请上传logo',
            'logo_pic.max' => '请上传logo',
            'contact_user.require' => '请填写联系人',
            'phone.require' => '请填写手机号',
            'address.require' => '请填写地址',
            'address.max' => '地址过长',
            'lat.require' => '请选择地址',
            'lat.float' => '请选择地址',
            'lng.require' => '请选择地址',
            'lng.float' => '请选择地址',
            'business_license_pic.require' => '请上传营业执照照片',
            'business_license_pic.max' => '请上传营业执照照片',
            'qrcode_pic.require' => '请上传小程序码',
            'qrcode_pic.max' => '请上传小程序码',
        ];
        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($data)) $this->error($validate->getError());
        $model = Shop::get($data['id']);
        if (!$model) {
            $this->error('店铺不存在');
        }
        $invite_code = $data['invite_code'];
        // $data['salesman_admin_id'] = 0;
        // if ($invite_code) {
        //     $data['salesman_admin_id'] = (int)Admin::where('salt',$invite_code)->value('id');
        // }
        // $data['business_time'] = json_encode($data['business_time']);
        $qrcode_pic = $data['qrcode_pic'];
        unset($data['invite_code']);
        unset($data['qrcode_pic']);
        $return = [];
        Db::startTrans();
        try {
            $save = array_merge($data, [
                'update_by' => $this->auth->nickname,
                // 'have_uid' => 1,
                // 'submit_by' => 1,
            ]);
            $result = $model->allowField(true)->save($save);
            $return = $model['id'];
            // 跟进业务员
            // if ($save['salesman_admin_id']) {
            //     ShopFollow::create([
            //         'shop_no' => $save['shop_no'],
            //         'follow_admin_id' => $save['salesman_admin_id'],
            //         'is_head' => 1,
            //     ]);
            // }
            // 平台信息
            $sp = ShopPlatform::where([
                'shop_no' => $model['shop_no'],
            ])->find();
            if ($qrcode_pic!=$sp['qrcode_pic']) {
                $sp->save([
                // 'platform_no' => $data['platform_no'],
                'qrcode_pic' => $qrcode_pic]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            \think\Log::write($_SERVER['REQUEST_URI'].'=>Exception:'.$e->getMessage());
            $this->error('店铺提交失败');

        }
        $this->success('提交成功',$return);
    }



    public function authorize()
    {
        $shop_no = input('shop_no', '','htmlspecialchars');
        $username = input('username', '','htmlspecialchars');
        $shop_type = input('shop_type', '','htmlspecialchars');
        $MeishikaiService = new \services\MeishikaiService();
        $meishikai = Db::name('meishikai')->where('id',1)->find();
        // $username = 'wmjlxj6517645';
        // if (Db::name('shop_authorize')->where(["username"=>$username,"is_success"=>1])->find()) {
        //     $this->error('店铺已授权');
        // }
        $shop_authorize = Db::name('shop_authorize')->where(['shop_no'=>$shop_no,"is_success"=>1])->find();
        if ($shop_authorize) $this->error('店铺已授权');
        $res = $MeishikaiService->setModel($meishikai['token'],$username,$shop_type);
        \think\Log::write('店铺授权第一步:'.$res);
        $decode = json_decode($res,1);
        if (!isset($decode['IsSuccess']) || !$decode['IsSuccess']) {
            if (!isset($decode['Message']) || $decode['Message']!='账号不存在或已过期') {
                $this->error('接口请求有误');
            }
            $res2 = $MeishikaiService->userLogin();
            $decode2 = json_decode($res2,1);
            if (!isset($decode2['Content']['Token']) || !$decode2['Content']['Token']) {
                $this->error('获取token参数失败');
            }
            Db::name('meishikai')->where('id',1)->update([
                'content' => $res2,
                'token' => $decode2['Content']['Token'],
                'update_dt' => date('Y-m-d H:i:s'),
                // 'expire_time' => strtotime($decode['Content']['DatExpired']),
                'expire_time' => time()+518400,
            ]);
            $meishikai['token'] = $decode2['Content']['Token'];
            $res = $MeishikaiService->setModel($meishikai['token'],$username,$shop_type);
            \think\Log::write('店铺授权第一步:'.$res);
            $decode = json_decode($res,1);
            if (!isset($decode['IsSuccess']) || !$decode['IsSuccess']) {
                $this->error('接口请求有误');
            }
        }
        if (Db::name('shop_authorize')->where(["accountid"=>$decode['Content']['ID'],"is_success"=>1])->find()) {
            $this->error('店铺已授权');
        }
        Db::name('shop_authorize')->insert([
            'accountid' => $decode['Content']['ID'],
            'content' => $res,
            'shop_no' => $shop_no,
            'update_dt' => date('Y-m-d H:i:s'),
            'username' => $username,
            'shop_name' => $decode['Content']['ShopName'],
        ]);
        $meishikai_content = json_decode($meishikai['content'],1);
        $username = $meishikai_content['Content']['UserName'];
        $accountid = $decode['Content']['ID'];
        $res = $MeishikaiService->mtAuthorize($meishikai['token'],$accountid,$username);
        \think\Log::write('店铺授权第2步:'.$res);
        $decode = json_decode($res,1);
        if (isset($decode['IsSuccess']) && $decode['IsSuccess']) {
            // Db::name('shop')->where('shop_no',$shop_no)->update(['is_auth'=>1]);
            $this->success('成功',$decode['Content']);
        } else {
            $this->error('接口请求有误');
        }
    }
}